/*
 * @Author: Ma Xiaohan
 * @Date: 2018-08-19 13:43:08
 * @Last Modified by: Xiaohan Ma
 * @Last Modified time: 2018-09-01 16:01:04
 */
import {omit} from '../utils/utils';
import {rmEmptyDirs} from '../utils/rmemptydirs';
const BasicModel = require('./BasicModel');
const fs = require('fs');
const path = require('path');

module.exports = class extends BasicModel {
  get relation() {
    return {
      project_files: {
        type: think.Model.HAS_MANY,
        model: 'project_files',
        key: 'id',
        fKey: 'project_id'
      },
      richtext: {
        type: think.Model.BELONG_TO,
        model: 'richtext',
        key: 'id',
        fKey: 'relation_id'
      }
    };
  }
  async getFilesListByIdAction(params) {
    const listall = this.model('project_files').where({project_id: params}).select();
    return listall;
  }
  async uploadfilesAction(params) {
    const data = this.model('project_files').add(params);
    return data;
  }

  async getUploadFileByIdAction(params) {
    const data = this.model('project_files').where({id: params.id}).find();
    return data;
  }

  async addAction(params) {
    const id = think.uuid('v4');
    params.data.id = id;
    const data = await this.thenAdd(params.data, {project_name: params.data.project_name});
    // const data = await this.model(params.model).add(params.data);
    const richTextData = {
      data: {}
    };
    richTextData.data.relation_id = id;
    richTextData.data.richtext = '';
    const richtext = await this.model('richtext').addAction(richTextData);
    if (data.type === 'add') {
      return {...richtext, ...data, id};
    }
    return {...richtext, ...data};
  }

  async getAction(params) {
    const data = await this.model(params.model).where({id: params.id}).find();
    const richText = await this.model('richtext').where({relation_id: params.id}).find();
    const projectfiles = await this.model('project_files').where({project_id: params.id}).select();
    // blob数据转string返回前端
    // richtext = richtext;
    let richtext = richText.richtext;
    if (think.isEmpty(richtext)) {
      richtext = '';
    }
    richtext = richtext.toString('utf-8');
    data.richtext = richtext;
    // if (think.isEmpty(projectfiles)) {
    //   data.project_files = [];
    // } else if (think.isObject(projectfiles)) {
    //   // const arr = [];
    //   // arr.push(data.project_files);
    //   // data.project_files = arr;
    //   data.project_files = [projectfiles];
    // }
    data.project_files = projectfiles;
    return data;
  }
  async editAction(params) {
    const richTextData = {
      data: {}
    };
    richTextData.data.richtext = params.data.richtext;
    richTextData.data.relation_id = params.data.id;
    const richtext = await this.model('richtext').editAction(richTextData);
    delete params.data.richtext;
    const data = this.model(params.model).where({ id: params.data.id }).update(params.data);
    return {...richtext, ...data};
  }

  // deleteFileAction(params) {
  //   const filesinfo = this.model('project_files').where({id: params.id}).delete();
  //   return filesinfo;
  // }
  // async delAction(params) {
  //   const richTextData = await this.model('richtext').where({relation_id: params.id}).delete();
  //   const projectInfoData = await this.model(params.model).where(params.data).delete();
  //   return {richTextData, projectInfoData};
  // }

  async deleteFileAction(params) {
    const filesinfo = await this.model('project_files').where({id: params.id}).find();
    if (think.isEmpty(filesinfo)) {
      return '文件不存在';
    }
    await fs.unlink(filesinfo.file_path, (err) => {
      if (err) {
        return err;
      }
      const dirpath = path.dirname(filesinfo.file_path);
      // 删除空文件夹
      rmEmptyDirs(dirpath);
    });
    await this.model('project_files').where({id: params.id}).delete();
    return '删除成功';
  }
  async delAction(params) {
    const richTextData = await this.model('richtext').where({relation_id: params.id}).delete();
    const projectfiles = await this.model('project_files').where({project_id: params.id}).delete();
    // 删除文件夹及文件夹下所有文件
    // const fileDirPath = `/home/mdalang/projects/mobile_internet_website_server/runtime/upload/projectFileInfo/${params.id}`;
    const fileDirPath = `/var/www/html/mobile_internet_website_server/runtime/upload/projectFileInfo/${params.id}`;
    await think.rmdir(fileDirPath, false);
    const projectInfoData = await this.model(params.model).where(params.data).delete();
    return {projectInfoData, richTextData, projectfiles};
  }

  async listallAction(params) {
    let data;
    var arr = Object.keys(params.data);// 传空返回全部数据，不为空选择查询
    if (arr.length !== 0) {
      data = this.order('project_start_time DESC').where({...params.data}).select();
      return data;
    } else {
      data = this.order('project_start_time DESC').select();
      return data;
    }
  }

  async listpageAction(params) {
    const searchData = omit(params.data, ['page', 'pageSize'], true);
    const key = Object.keys(searchData)[0];
    const value = searchData[key];
    // 去查询条件的第一个进行模糊查询
    let fuzzyQueryData = {};
    if (think.isEmpty(key)) {
      fuzzyQueryData = {};
    } else {
      fuzzyQueryData[key] = ['like', `%${value}%`];
    }
    const { page = 1, pageSize = 20 } = params.data;
    const dataList = await this.order('create_time DESC').where(fuzzyQueryData).page(page, pageSize).countSelect();
    const {
      currentPage: current,
      totalPages: pages,
      count: total,
      data
    } = dataList;
    return { pageSize, pages, current, total, data };
  }
  // 前台展示接口
  async getlistAction(params) {
    const searchData = omit(params.data, ['page', 'pageSize'], true);
    const key = Object.keys(searchData)[0];
    const value = searchData[key];
    // 去查询条件的第一个进行模糊查询
    let fuzzyQueryData = {};
    if (think.isEmpty(key)) {
      fuzzyQueryData = {};
    } else {
      fuzzyQueryData[key] = ['like', `%${value}%`];
    }
    const { page = 1, pageSize = 20 } = params.data;
    const dataList = await this.order('create_time DESC').where(fuzzyQueryData).page(page, pageSize).countSelect();
    return dataList;
  }
  async getoneAction(params) {
    return this.where({id: params.id}).find();
  }
};
